package com.nervenets.web.controller.handler.user.wealth;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.FlowStatus;
import com.nervenets.web.enumeration.OperateType;
import com.nervenets.web.enumeration.UnionType;
import com.nervenets.web.enumeration.WealthType;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.rabbitmq.FlowMessage;
import com.nervenets.web.redis.domain.global.GlobalRule;
import com.nervenets.web.redis.utils.ISyncExecutor;
import org.weixin4j.WeixinException;

import javax.servlet.http.HttpServletRequest;

public class UserWithdrawHandler extends Handler<UserWithdrawParams> {
    @Override
    public String handle(UserWithdrawParams params, HttpServletRequest request) throws Exception {
        if (!globalVariablesService.canProceed(params.getUserId())) return errorMessage(MessageCode.code_505);

        User user = userDao.findById(params.getUserId(), User.class);
        if (null == user) return errorMessage(MessageCode.code_778);

        if (StringUtils.isEmpty(user.getWechatId())) {
            return errorMessage(MessageCode.code_444, "您还没有绑定微信，请先绑定微信！");
        }

        final org.weixin4j.User userInfo;
        try {
            userInfo = Global.getWeixin().getUserInfo(user.getWechatId());
        } catch (WeixinException e) {
            if (e.shouldReLogin()) {
                weixinLogin();
                return errorMessage(MessageCode.code_301);
            }
            throw e;
        }
        //判断是否关注公众号
        if ("0".equals(userInfo.getSubscribe())) {
            return errorMessage(MessageCode.code_443);
        }

//        final GlobalRule globalRule = globalVariablesService.getGlobalRule();
        return (String) redisSyncLocker.keyLock(String.format(Global.Constants.REDIS_USER_WEALTH_LOCK, params.getUserId()), (ISyncExecutor<String, Object>) o -> {

            long surplus = globalService.getUserWealthOfMoney(params.getUserId(), WealthType.money);
            if (surplus < params.getMoney()) return errorMessage(MessageCode.code_444, "余额不足");

            messageProducer.flow(FlowMessage.wealthChange(params.getUserId(), getIp(request), UnionType.normal, 0, -params.getMoney(), OperateType.withdraw, params.getPayType(), FlowStatus.handling, "提现"));

            return successMessage(surplus - params.getMoney());
        }, null);
    }

    @Override
    public String result() {
        return null;
    }
}
